import atexit
import datetime
import json
import os
import time

import dashscope
import pyaudio
from dashscope.audio.asr import RecognitionCallback, RecognitionResult, Recognition

dashscope.api_key = os.environ['DASHSCOPE_API_KEY']
mic = None
stream = None


class Callback(RecognitionCallback):
    def on_open(self) -> None:
        global mic
        global stream
        print('RecognitionCallback open.')
        mic = pyaudio.PyAudio()
        stream = mic.open(format=pyaudio.paInt16,
                          channels=1,
                          rate=16000,
                          input=True)

    def on_close(self) -> None:
        global mic
        global stream
        print('RecognitionCallback close.')
        stream.stop_stream()
        stream.close()
        mic.terminate()
        stream = None
        mic = None

    def on_event(self, result: RecognitionResult) -> None:
        timestamp = get_timestmp()
        sentence = json.dumps(result.get_sentence(), ensure_ascii=False)
        print('RecognitionCallback sentence: ', timestamp, sentence)
        with open('myfile.txt', 'a', encoding='utf-8') as file:
            file.write(str(timestamp) + ' => ' + sentence + '\n')


callback = Callback()
recognition = Recognition(model='paraformer-realtime-v1',
                          format='pcm',
                          sample_rate=16000,
                          callback=callback)


def recognition_stop():
    recognition.stop()


atexit.register(recognition_stop)


def read():
    while True:
        if stream:
            data = stream.read(3200, exception_on_overflow=False)
            recognition.send_audio_frame(data)
        else:
            break


def get_timestmp():
    # 获取当前时间
    now = datetime.datetime.now()

    # 转换为时间戳（秒），然后转换为毫秒
    timestamp_ms = int(time.time() * 1000)

    # 或者使用datetime模块，但这种方法稍微复杂一些
    timestamp_ms_alt = int(now.timestamp() * 1000)

    # 获取微秒部分并转换为毫秒
    microseconds = now.microsecond // 1000
    timestamp_ms_full = timestamp_ms_alt + microseconds
    return timestamp_ms_full
